//
//  NSStringAdditions.m
//  MoCard
//
//  Created by 水石 温 on 11-9-23.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "NSStringCatalog.h"

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>

#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

@implementation NSString (DDXML)

- (const xmlChar *)xmlChar
{
	return (const xmlChar *)[self UTF8String];
}


#ifdef GNUSTEP
- (NSString *)stringByTrimming
{
	return [self stringByTrimmingSpaces];
}
#else
- (NSString *)stringByTrimming
{
	NSMutableString *mStr = [self mutableCopy];
	CFStringTrimWhitespace((CFMutableStringRef)mStr);
	
	NSString *result = [mStr copy];
	
	return result;
}
#endif

-(NSString*)trim {
    //只能去除前后的空格
    NSMutableCharacterSet *trimCharSet=[NSMutableCharacterSet whitespaceCharacterSet];
    return [self stringByTrimmingCharactersInSet:trimCharSet];
    
}

-(NSString*)trimAll {
    NSMutableString *result=[[NSMutableString alloc] init];
    for (int i=0;i<self.length;i++) {
        NSString* chr = [self substringWithRange:NSMakeRange(i, 1)];
        if ( ! [chr isEqualToString:@" "]) {
            [result appendString:chr];
        }
    }
    return result;
}
- (UIColor *)getRGBColor
{
    if ([self length] == 6){
        unsigned int red,green,blue;
        NSRange range;
        range.length = 2;
        range.location = 0;
        [[NSScanner scannerWithString:[self substringWithRange:range]] scanHexInt:&red];
        range.location = 2;
        [[NSScanner scannerWithString:[self substringWithRange:range]] scanHexInt:&green];
        range.location = 4;
        [[NSScanner scannerWithString:[self substringWithRange:range]] scanHexInt:&blue];
        return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
    }else{
        return [UIColor whiteColor];
    }
}

-(NSString*)fileIdFromUrl {
    NSRange fileIdRange=[self rangeOfString:@"fileid="];
    if (fileIdRange.location==NSNotFound) {
        return self;
    }
    NSString *fileId=[self substringFromIndex:fileIdRange.location+fileIdRange.length];
    fileIdRange=[fileId rangeOfString:@"&"];
    if (fileIdRange.location==NSNotFound) {
        return fileId;
    }
    return [fileId substringToIndex:fileIdRange.location];
}
-(NSString*)fileIdFromWeiboUrl {
    NSRange fileIdRange = [self rangeOfString:@"50/"];
    if (fileIdRange.location == NSNotFound) {
        return self;
    }
    NSString *fileId=[self substringFromIndex:fileIdRange.location+fileIdRange.length];
    fileIdRange=[fileId rangeOfString:@"&"];
    if (fileIdRange.location==NSNotFound) {
        return fileId;
    }
    return [fileId substringToIndex:fileIdRange.location];
}
-(NSString*)fileIdFromCache {
    NSRange fileIdRange=[self rangeOfString:@"cache/"];
    if (fileIdRange.location==NSNotFound) {
        return self;
    }
    NSString *fileId=[self substringFromIndex:fileIdRange.location+fileIdRange.length];
    fileIdRange=[fileId rangeOfString:@"&"];
    if (fileIdRange.location==NSNotFound) {
        return fileId;
    }
    return [fileId substringToIndex:fileIdRange.location];
}
//added by youq for meach 2.0 bug
-(NSString*)fileIdFromDocuments{
    NSRange fileIdRange=[self rangeOfString:@"Documents/"];
    if (fileIdRange.location==NSNotFound) {
        return self;
    }
    NSString *fileId=[self substringFromIndex:fileIdRange.location+fileIdRange.length];
    fileIdRange=[fileId rangeOfString:@"&"];
    if (fileIdRange.location==NSNotFound) {
        return fileId;
    }
    return [fileId substringToIndex:fileIdRange.location];
}
-(NSString*)fileIdFromChatPhoto{
    NSRange fileIdRange=[self rangeOfString:@"chatPhoto/"];
    if (fileIdRange.location==NSNotFound) {
        return self;
    }
    NSString *fileId=[self substringFromIndex:fileIdRange.location+fileIdRange.length];
    fileIdRange=[fileId rangeOfString:@"&"];
    if (fileIdRange.location==NSNotFound) {
        return fileId;
    }
    return [fileId substringToIndex:fileIdRange.location];
}



- (BOOL)validateAsEmail {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

-(NSString*)shortJid {
    if ([self rangeOfString:@"/"].location!=NSNotFound) {
        NSString *jid=[[self componentsSeparatedByString:@"/"] objectAtIndex:0];
        return jid;
    }
    return self;
}
-(NSString*)userName{
    if ([self rangeOfString:@"@"].location != NSNotFound) {
        NSString *username = [[self componentsSeparatedByString:@"@"] objectAtIndex:0];
        return username;
    }
    return self;
}
-(NSInteger)appVersionIntValue {
    //为方便版本号比较，传进来vx.x.x或x.x.x,返回xxx整数。
    if ([self length]==0) {
        return 0;
    }
    NSString *temp=([self hasPrefix:@"v"] ? [self substringFromIndex:1] : self);
    
    return [[temp stringByReplacingOccurrencesOfString:@"." withString:@""] intValue];
}
NSString* timeStringWithDate(NSDate *date){
	
	NSString *dateInterval = nil;
    NSTimeInterval timeInterval = - [date timeIntervalSinceNow];
	if(timeInterval < 60){
		dateInterval = STR(@"刚刚");
	}else if (timeInterval < 3600) {
		dateInterval = [NSString stringWithFormat:STR(@"%.0f分钟前"),timeInterval/60];
	}else if (timeInterval < 86400) {
		dateInterval = [NSString stringWithFormat:STR(@"%.0f小时前"),timeInterval/3600];
	}else {
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setDateFormat:@"MM-dd"];
		dateInterval = [formatter stringFromDate:date];
	}
	
	return dateInterval;
}
NSString* timeIntervalStringWithTimeString(NSDate *date){
	
	NSString *dateInterval = nil;
	
	//NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSTimeInterval timeInterval = - [date timeIntervalSinceNow];
	
	if(timeInterval < 60){
		dateInterval = STR(@"刚刚");
	}else if (timeInterval < 3600) {
		dateInterval = [NSString stringWithFormat:STR(@"%.0f分钟前"),timeInterval/60];
	}else if (timeInterval < 86400) {
		dateInterval = [NSString stringWithFormat:STR(@"%.0f小时前"),timeInterval/3600];
	}else if (timeInterval < 86400*365){
		dateInterval = [NSString stringWithFormat:STR(@"%.0f 天前"),timeInterval/86400];
	}
    else if(timeInterval < 86400*365*60){
        dateInterval = [NSString stringWithFormat:STR(@"%.0f年前"),timeInterval/(86400*365)];
    }
    else {
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setDateFormat:@"YYYY-MM-dd"];
		dateInterval = [formatter stringFromDate:date];
	}
	
	return dateInterval;
}
-(NSString*)calculateConstellationFromBirthdayStr {
    NSArray *sub=[self componentsSeparatedByString:@"-"];
    if (sub.count==3) {
        NSInteger month=[[sub objectAtIndex:1] integerValue];
        NSInteger day=[[sub objectAtIndex:2] integerValue];
        switch (month) {
            case 1:
                if (day<=19) {
                    return STR(@"摩羯座");
                } else {
                    return STR(@"水瓶座");
                }
                break;
            case 2:
                if (day<=18) {
                    return STR(@"水瓶座");
                } else {
                    return STR(@"双鱼座");
                }
                break;
            case 3:
                if (day<=20) {
                    return STR(@"双鱼座");
                } else {
                    return STR(@"白羊座");
                }
                break;
            case 4:
                if (day<=19) {
                    return STR(@"白羊座");
                } else {
                    return STR(@"金牛座");
                }
                break;
            case 5:
                if (day<=20) {
                    return STR(@"金牛座");
                } else {
                    return STR(@"双子座");
                }
                break;
            case 6:
                if (day<=21) {
                    return STR(@"双子座");
                } else {
                    return STR(@"巨蟹座");
                }
                break;
            case 7:
                if (day<=22) {
                    return STR(@"巨蟹座");
                } else {
                    return STR(@"狮子座");
                }
                break;
            case 8:
                if (day<=22) {
                    return STR(@"狮子座");
                } else {
                    return STR(@"处女座");
                }
                break;
            case 9:
                if (day<=22) {
                    return STR(@"处女座");
                } else {
                    return STR(@"天秤座");
                }
                break;
            case 10:
                if (day<=23) {
                    return STR(@"天秤座");
                } else {
                    return STR(@"天蝎座");
                }
                break;
            case 11:
                if (day<=22) {
                    return STR(@"天蝎座");
                } else {
                    return STR(@"射手座");
                }
                break;
            case 12:
                if (day<=21) {
                    return STR(@"射手座");
                } else {
                    return STR(@"摩羯座");
                }
                break;
        }
    }
    return @"";
}
#define kDEFAULT_DATE_TIME_FORMAT (@"yyyy-MM-dd'T'HH:mm:ss'Z'")
#define SHORT_DATE_TIME_FORMAT @"HH:mm"
#define LONG_DATE_TIME_FORMAT (@"MM-dd HH:mm")

- (NSString*) HMACWithSecret:(NSString*) secret
{
    CCHmacContext    ctx;
    const char       *key = [secret UTF8String];
    const char       *str = [self UTF8String];
    unsigned char    mac[CC_MD5_DIGEST_LENGTH];
    char             hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];
    char             *p;
    
    CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key ));
    CCHmacUpdate( &ctx, str, strlen(str) );
    CCHmacFinal( &ctx, mac );
    
    p = hexmac;
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) {
        snprintf( p, 3, "%02x", mac[ i ] );
        p += 2;
    }
    
    return [NSString stringWithUTF8String:hexmac];
}

-(int)getNameLength{
    NSString* str = [self trim];
    int len = 0;
    for (int i=0; i<[str length];i++ ) {
        unichar c = [str characterAtIndex:i];
        len += [self charLen:c];
    }
    return len;
}
-(int)charLen:(unichar)c
{

    if (c>=0xa1){
        if (c==0xa3)
            return 2;	//全角字符
        else
            return 2;	//汉字
    }else
        return 1;	 //英文、数字、英文标点
    
}

@end
